﻿@{
    ViewBag.Title = T("Roles");
}
<script src="~/Scripts/knockout-2.2.1.debug.js"></script>
@*<script src="~/Scripts/knockout.mapping-latest.debug.js"></script>*@
<script src="~/Scripts/jquery.validate.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js" type="text/javascript"></script>
<script src="~/Scripts/sammy-0.7.4.min.js" type="text/javascript"></script>

<script type="text/javascript">
    var RolesViewModel = function () {
        var self = this;
        self.Name = ko.observable("");
        //Array for Storing the JSON Response
        self.Roles = ko.observableArray([]);
        self.SelectedRole = ko.observable(null);
        self.Members = ko.observableArray([]);
        self.AllUsers = ko.observableArray([]);

        GetRoles();

        self.submitHandler = function () {
            console.log("SUMBIT handler");
            var form = $("#addRoleForm");
            var validator = form.validate();
            var roleNameValid = validator.valid();
            console.log("Submit. roleNameValid:", roleNameValid);
            if (roleNameValid) {
                self.insert();
                form[0].reset();
            }

            return false;
        };

        self.insert = function () {
            console.log("insert");

            //Convert the Observable Data into JSON
            var dataToSend = ko.toJSON(self.Name);
            console.log("Insert. Data to send: " + dataToSend);
            $.ajax({
                type: "POST",
                url: "/api/Roles/Insert",
                data: dataToSend,
                contentType: "application/json",
                success: function (data) {
                    console.log("Record Added Successfully");
                    self.Name(null);
                    GetRoles();
                },
                error: function (error) {
                    console.log(error);
                    var responseText = $.parseJSON(error.responseText);
                    if (responseText.Message === undefined)
                        alert(responseText);
                    else
                        alert(responseText.Message);
                }
            });
        };

        self.deleteRole = function (role) {
            if (!confirm('@T("Are you sure you want to DELETE the role \"{0}\"?")'.replace('{0}', role.Name))) {
                return;
            }
            self.Name(null);
            $.ajax({
                type: "DELETE",
                url: "/api/Roles/Delete/",
                data: ko.toJSON(role.Name),
                contentType: "application/json",
                success: function (data) {
                    console.log("Record Deleted Successfully");
                    GetRoles();
                },
                error: function (error) {
                    alert(error.status + "<--and--> " + error.statusText);
                }
            });
        };

        self.addToRole = function (user) {
            var dataToSend = { userName: user.Name, roleName: self.SelectedRole() };
            $.ajax({
                type: "POST",
                url: "/api/Roles/AddUserToRole",
                data: ko.toJSON(dataToSend),
                contentType: "application/json",
                success: function (data) {
                    console.log("Role added for user successfully");
                    GetUsersInRole(self.SelectedRole());
                    self.AllUsers.remove(user);
                },
                error: function (error) {
                    ErrorHandler(error);
                }
            });
        };

        self.removeUserFromRole = function (user) {
            var dataToSend = { userName: user.Name, roleName: self.SelectedRole() };
            $.ajax({
                type: "POST",
                url: "/api/Roles/RemoveUserFromRole",
                data: ko.toJSON(dataToSend),
                contentType: "application/json",
                success: function (data) {
                    console.log("Role removed for user successfully");
                    GetUsersInRole(self.SelectedRole());
                    self.AllUsers.push(user);
                },
                error: function (error) {
                    ErrorHandler(error);
                }
            });
        };

        self.manageRole = function (role) {
            console.log("manageRole: ", role);
            location.hash = "ManageRole" + "/" + role.Name;
        };

        self.backToRoleList = function () {
            console.log("Back to role list");
            location.hash = "#/";
        };

        function ErrorHandler(error) {
            console.log(error);
            var alertMessage = error.status + "\r\n" + error.statusText;
            var response = eval("(" + error.responseText + ")");
            if (response.Message != undefined)
                alertMessage += "\r\n" + response.Message;
            alert(alertMessage);
        };

        function GetRoles() {
            console.log("GetRoles");
            //console.log("Hash: " + location.hash);
            $.ajax({
                type: "GET",
                url: "/api/Roles/GetAll",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    console.log("GetRoles.success: ", data);
                    self.Roles(data);
                },
                error: function (error) {
                    ErrorHandler(error);
                }
            });
        };

        function GetUsersInRole(roleName) {
            console.log("GetUsersInRole: '" + roleName + "'");
            $.ajax({
                type: "GET",
                url: "/api/Roles/GetUsersInRole/" + roleName, //encodeURIComponent(roleName),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    console.log("GetUsersInRole.success: ", data);
                    self.Members(data);
                },
                error: function (error) {
                    ErrorHandler(error);
                }
            });
        };

        function GetAllUsers() {
            console.log("GetAllUsers");
            //AllUsers
            $.ajax({
                type: "GET",
                url: "/api/Roles/GetAllUsers/" + self.SelectedRole(),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    console.log("GetAllUsers.success: ", data);
                    self.AllUsers(data);
                },
                error: function (error) {
                    ErrorHandler(error);
                }
            });
        }

        // Client-side routes    
        Sammy("#routingArrea", function () {
            this.get('#ManageRole/:roleName', function () {
                //console.log("SammyGet");
                self.Roles(null);
                self.SelectedRole(this.params.roleName);
                GetUsersInRole(this.params.roleName);
                GetAllUsers();
            });

            //this.get('', function () { this.app.runRoute('get', '#Inbox') });
            this.get('#/', function () {
                //console.log("Route ####");
                self.SelectedRole(null);
                GetRoles();
            });
        }).run();
    };

    $(document).ready(function () {
        ko.applyBindings(new RolesViewModel());
    });
</script>

<ul class="path floatContainer">
    <li class="first">@ActionLinkLocalized("Main", "Index", "Home")</li>
	<li>@ActionLinkLocalized("Admin", "Dashboard", "Admin")</li>
</ul>


<form id="addRoleForm" data-bind="submit: $root.submitHandler, visible: $root.Roles() != null">
    <h1>@T("Roles")</h1>
    <div class="formItem floatContainer">
        <label for="newRoleName" style="width: 70px">@T("New role:")</label>
        <input type="text" id="newRoleName" name="newRoleName" data-bind="value: $root.Name" 
            data-val="true" 
            data-val-required='@T("Enter a role name")'
            class="input-validation-error" />
        <span class="field-validation-valid" data-valmsg-for="newRoleName" data-valmsg-replace="true"/>
    </div>
    <div class="formItem buttons floatContainer" style="padding-top: 10px;padding-bottom:10px">
	    <input type="submit" value="@T("Add")"/>
    </div>
</form>

<div id="routingArrea">
    <!-- ko with: $root.SelectedRole -->
    <a href="#" data-bind="click: $root.backToRoleList">@T("Back")</a>
    <!-- /ko -->

    <div class="floatContainer">
    
        <!-- ko with: Roles -->
        <table class="admin" data-bind="visible: length>0">
            <thead>
                <tr>
                    <th></th>
                    <th>@T("Role Name")</th>
                </tr>
            </thead>
            <tbody data-bind="foreach: $root.Roles">
                <tr>
                    <td>
                        <span class="actions">
							<a href="#" data-bind="click: $root.manageRole">@T("Edit")</a>
							<a href="#" data-bind="click: $root.deleteRole">@T("Delete")</a>
                        </span>
                    </td>
                    <td>
                        <strong data-bind="text: Name"></strong>
                    </td>
                </tr>
            </tbody>
        </table>
        <!-- /ko -->
        <!-- ko with: $root.SelectedRole -->
        <div class="leftFloatItem25">
            <table class="admin">
                <thead>
                    <tr>
                        <th colspan="2">@T("Users in role")&nbsp;'<span data-bind="text: $root.SelectedRole"/>'</th>
                    </tr>
                    <tr>
                        <th></th>
                        <th>@T("Member Name")</th>
                    </tr>
                </thead>
                <tbody data-bind="foreach: $root.Members">
                    <tr>
                        <td>
                            <span class="actions"><a href="#" data-bind="click: $root.removeUserFromRole">@T("Delete")</a></span>
                        </td>
                        <td>
                            <strong data-bind="text: Name"></strong>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
        <div class="leftFloatItem25">
        <table class="admin">
            <thead>
                <tr>
                    <th colspan="2">@T("Available users")</th>
                </tr>
                <tr>
                    <th></th>
                    <th>@T("User's name")</th>
                </tr>
            </thead>
            <tbody data-bind="foreach: $root.AllUsers">
                <tr>
                    <td>
                        <span class="actions"><a href="#" data-bind="click: $root.addToRole">@T("Add")</a></span>
                    </td>
                    <td>
                        <strong data-bind="text: Name"></strong>
                    </td>
                </tr>
            </tbody>
        </table>
        </div>
        <!-- /ko -->
    </div>
    <!-- ko with: $root.SelectedRole -->
    <a href="#" data-bind="click: $root.backToRoleList">@T("Back")</a>
    <!-- /ko -->
</div>